<template>
  <div class="chat-window">
    <div class="chat-header">
      <a-button shape="circle" @click="goBack">
        <template #icon>
          <IconArrowLeft />
        </template>
      </a-button>
      <a-avatar :style="{ backgroundColor: chatInfo.avatarColor }" size="large">
        {{ chatInfo.name[0] }}
      </a-avatar>
      <h3>{{ chatInfo.name }}</h3>
    </div>
    <div class="chat-content">
      <div
        v-for="message in messages"
        :key="message.id"
        class="message"
        :class="{ 'editable-message': isEditMode }"
      >
        <a-avatar :style="{ backgroundColor: message.avatarColor }">
          {{ message.name ? message.name[0] : 'A' }}
        </a-avatar>
        <div class="message-content">
          <div class="message-name">{{ message.name }}</div>
          <div v-if="message.type === 'text'">{{ message.text }}</div>
          <img v-else :src="message.text" alt="Message Image" class="message-image" />
        </div>
        <div v-if="isEditMode" class="message-actions">
          <a-button type="text" @click="openEditMessageModal(message)">编辑</a-button>
          <a-button type="text" @click="deleteMessage(message.id)">删除</a-button>
        </div>
      </div>
    </div>
    <div class="chat-footer">
      <div class="chat-input">
        <a-input v-model="newMessage" placeholder="输入消息" @press-enter="sendMessage" />
        <a-upload
          accept="image/*"
          :custom-request="customRequest"
          :before-upload="false"
        >
          <a-button type="primary">上传图片</a-button>
        </a-upload>
      </div>
    </div>

    <!-- 编辑消息模态框 -->
    <a-modal v-model:visible="isEditMessageModalVisible" title="编辑消息" @ok="saveEditMessage">
      <a-form>
        <a-form-item label="发送人名字">
          <a-input v-model="editMessageName" placeholder="请输入发送人名字" />
        </a-form-item>
        <a-form-item label="头像颜色">
          <a-color-picker v-model="editMessageAvatarColor" />
        </a-form-item>
        <a-form-item label="信息类型">
          <a-radio-group v-model="editMessageType">
            <a-radio value="text">文本</a-radio>
            <a-radio value="image">图片</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="信息内容">
          <a-input v-model="editMessageText" placeholder="请输入信息内容" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { computed, ref } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { IconArrowLeft } from '@arco-design/web-vue/es/icon';

export default {
  components: {
    IconArrowLeft,
  },
  props: {
    chatInfo: {
      type: Object,
      required: true,
    },
  },
  setup(props) {
    const store = useStore();
    const router = useRouter();
    const isEditMode = computed(() => store.state.isEditMode);

    const newMessage = ref('');
    const newMessageText = ref('');
    const newMessageType = ref('text');
    const messages = ref([]);

    const editMessageId = ref(null);
    const editMessageName = ref('');
    const editMessageAvatarColor = ref('#1890ff');
    const editMessageText = ref('');
    const editMessageType = ref('text');
    const isEditMessageModalVisible = ref(false);

    const loadMessages = () => {
      return JSON.parse(localStorage.getItem(`messages_${props.chatInfo.id}`)) || [];
    };

    const saveMessages = () => {
      localStorage.setItem(`messages_${props.chatInfo.id}`, JSON.stringify(messages.value));
    };

    const sendMessage = () => {
      const messageContent = newMessageText.value || newMessage.value;
      if (!messageContent) return;

      const newMessageObj = {
        id: messages.value.length + 1,
        name: '我',
        avatarColor: '#87d068',
        text: messageContent,
        type: newMessageType.value,
      };
      messages.value.push(newMessageObj);
      saveMessages();

      newMessage.value = '';
      newMessageText.value = '';
      newMessageType.value = 'text';
    };

    const customRequest = (option) => {
      const { onProgress, onError, onSuccess, fileItem } = option;
      const reader = new FileReader();

      reader.onload = (e) => {
        const base64 = e.target.result;
        newMessageText.value = base64;
        newMessageType.value = 'image';
        onSuccess('ok');
      };

      reader.onerror = (error) => {
        onError(error);
      };

      reader.readAsDataURL(fileItem.file);

      return {
        abort() {
          reader.abort();
        },
      };
    };

    const deleteMessage = (id) => {
      messages.value = messages.value.filter((msg) => msg.id !== id);
      saveMessages();
    };

    const openEditMessageModal = (message) => {
      editMessageId.value = message.id;
      editMessageName.value = message.name;
      editMessageAvatarColor.value = message.avatarColor;
      editMessageText.value = message.text;
      editMessageType.value = message.type;
      isEditMessageModalVisible.value = true;
    };

    const saveEditMessage = () => {
      const message = messages.value.find((msg) => msg.id === editMessageId.value);
      if (message) {
        message.name = editMessageName.value;
        message.avatarColor = editMessageAvatarColor.value;
        message.text = editMessageText.value;
        message.type = editMessageType.value;
        saveMessages();
      }
      isEditMessageModalVisible.value = false;
    };

    const goBack = () => {
      router.push('/');
    };

    messages.value = loadMessages();

    return {
      isEditMode,
      newMessage,
      newMessageText,
      newMessageType,
      messages,
      sendMessage,
      customRequest,
      deleteMessage,
      openEditMessageModal,
      saveEditMessage,
      isEditMessageModalVisible,
      editMessageId,
      editMessageName,
      editMessageAvatarColor,
      editMessageText,
      editMessageType,
      goBack,
    };
  },
};
</script>

<style scoped>
.chat-window {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-header {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eaeaea;
}

.chat-header .a-avatar {
  margin-right: 10px;
}

.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.message {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.message-content {
  margin-left: 10px;
}

.message-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.message-image {
  max-width: 100%;
  height: 200px; /* 设置固定高度 */
  object-fit: cover; /* 确保图片覆盖整个区域 */
}

.message-actions {
  margin-left: 10px;
}

.chat-footer {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  border-top: 1px solid #eaeaea;
}

.chat-input {
  display: flex;
  align-items: center;
  flex: 1;
}

.chat-actions {
  display: flex;
  align-items: center;
}
</style>